import time
from seleniumwire import webdriver
import requests
import os
import conf
import asyncio
from icecream import ic
import re
import json
import logging

class BuildQueryRequest:

    def get_douyin_download_request_main_content(self,main_url:str = conf.target_creator_url,run_for_cookie:bool=False) :

        if main_url == None:
            print('没有主页页面链接，请检查')
            return None
        target_str = 'https://www.douyin.com/aweme/v1/web/aweme/post/?'
        pattern = 'https://www\.douyin\.com/aweme/v1/web/aweme/post/.*'
        # options = webdriver.ChromeOptions()
        # options.add_experimental_option('excludeSwitches', ['enable-automation'])
        # options.add_experimental_option('useAutomationExtension', False)
        # options.add_argument(
        #     'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36')
        driver = webdriver.Chrome()
        driver.implicitly_wait(10)
        driver.get(main_url)
        target_requests_list = []
        first_params_dict={}
        req_cookie_dict = {}
        #首次或请求核心数据文件删除，需要重新判断并生成，如果存在则直接使用。失效情况待完善
        if not os.path.isfile(conf.request_main_content_file_path) or run_for_cookie == True:
            # 要处理人机验证
            try:
                verify_windows=driver.find_element(by='id',value='captcha_container')
                if verify_windows.is_displayed():
                    print('发现人机验证模块，等待验证----')
                    while True:
                        if verify_windows.is_displayed():
                            time.sleep(1)
                            continue
                        else:
                            print('人机验证通过')
                            driver.refresh()
                            break
            except Exception as e:
                print("没有定位到验证元素")
            # 获取cookie
            cookies_list = driver.get_cookies()
            req_cookie_dict = {cookie_item['name']: cookie_item['value'] for cookie_item in cookies_list}
            # 获取请求
            for req in driver.requests:
                if req.url.startswith('https://www.douyin.com/aweme/v1/web/aweme/post/'):
                    target_requests_list.append(req)
            # 获取请求头
            req_target_header_list = target_requests_list[0].headers
            print(type(req_target_header_list))
            req_target_header_dict = {}
            for key, value in req_target_header_list.items():
                req_target_header_dict[key] = value

            # 获取请求参数
            req_target_params_dict = target_requests_list[0].params
            # 有些参数值是列表，需要处理
            for key, value in req_target_params_dict.items():
                if isinstance(value, list):
                    print(f"键 '{key}' 的值是一个列表。")
                    req_target_params_dict[key] = value[0]
                    print(f"键 '{key}' 的值被修改为 '{req_target_params_dict[key]}'。")
            # 构造请求
            query_string = "&".join([f"{key}={value}" for key, value in req_target_params_dict.items()])
            send_url = f"{target_str}{query_string}"
            # 获取主页作者id
            sec_user_id = req_target_params_dict['sec_user_id']
            print(sec_user_id)
            # 首次自动获取以后保存成文件
            data_ready_write={
                "sec_user_id":sec_user_id,
                "url":send_url,
                "headers":req_target_header_dict,
                "cookies":req_cookie_dict,
            }
            json_data=json.dumps(data_ready_write)
            print('正在生成文件')
            with open(conf.request_main_content_file_path, 'w') as f:
                f.write(json_data)
            #
            # res=requests.get(url=send_url,headers=req_target_header_dict)
            # print(res.text)

            return {"url": send_url, "headers": req_target_header_dict}

        else:
            #文件已存在，测试文件是否失效
            pass


    def get_info_by_file(self):
        pass

    def get_info_by_webdriver(self):
        pass


    # 返回全部的视频信息
    def get_video_info(self,*args,**kwargs):
        '''
        获取视频信息
        :param args:需要修改的查询参数
        :param kwargs:接口参数，get_douyin_download_request_main_content方法返回
        :return:
        '''
        if not os.path.isfile(conf.request_main_content_file_path):
            # 查询请求核心文件内容
            print('请求核心数据文件不存在，正在获取')
            mian_content=self.get_douyin_download_request_main_content()
            url=mian_content['url']
            headers=mian_content['headers']
            res = requests.get(url=url, headers=headers)
            print(res.text)
            return res.text
        else:
            print('读取文件,并测试请求核心数据是否已失效')
            with open(conf.request_main_content_file_path, 'r') as f:
                data = f.read()
                mian_content = json.loads(data)
                url = mian_content['url']
                headers = mian_content['headers']
                res=requests.get(url=url,headers=headers)
                if res.text == '':
                    print('数据已失效，正在通过页面重新获取')
                    mian_content = self.get_douyin_download_request_main_content(run_for_cookie=True)
                    if mian_content == None:
                        print('构建请求核心数据已失效且重新获取失败，请重试')
                        return None
                else:
                    print('请求核心数据有效，直接返回查询结果')
                    return res.text



if __name__ == '__main__':
    BuildQueryRequest().get_video_info()

